package org.ihelpuoo.weboo.upload.index;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;

import javax.imageio.ImageIO;

import org.ihelpuoo.core.Nut;
import org.ihelpuoo.io.FileUtils;

public abstract class StaticIndexMaker extends AbstractIndexMaker
{

	public static void main(String[] args) throws Exception
	{
		IndexMakerFactory imf = IndexMakerFactory.me(Nut.me());
		File org = FileUtils.findFile("D:/_TEMP/QQ.wav");
		IndexMaker im = imf.getMaker(org);
		File indexed = new File("D:/_TEMP/abc.JPG");
		try
		{
			im.make(org,indexed,60,70);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	private static String	TYPE_HOME	= "upload/mime";
	private static String	EXTENSION	= ".jpg";

	private String			ext;

	public StaticIndexMaker(String extension)
	{
		ext = extension;
	}

	@Override
	public void make(File org, File indexed, int w, int h) throws UnacceptableFileException,
			FailToSaveIndexException
	{
		super.make(org,indexed,w,h);
		File iconFile = FileUtils.findFile(TYPE_HOME + "/" + ext + EXTENSION);
		if (null == iconFile || !iconFile.exists())
			throw new UnacceptableFileException("Can not find icon for \"" + ext + "\"!");
		BufferedImage icon;
		BufferedImage img;
		try
		{
			icon = ImageIO.read(iconFile);
			img = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
			Graphics gc = img.getGraphics();
			gc.setColor(Color.WHITE);
			gc.fillRect(0,0,img.getWidth(),img.getHeight());
			if (icon.getWidth() < img.getWidth() && icon.getHeight() < img.getHeight())
			{
				// draw in center
				int x = (img.getWidth() - icon.getWidth()) / 2;
				int y = (img.getHeight() - icon.getHeight()) / 2;
				gc.drawImage(icon,x,y,Color.WHITE,null);
			}
			else
			{
				float iconWH = new BigDecimal(icon.getWidth()).divide(
						new BigDecimal(icon.getHeight()),precision).floatValue();
				float imgWH = new BigDecimal(w).divide(new BigDecimal(h),precision).floatValue();
				if (iconWH > imgWH)
				{
					int oH = (int)(icon.getWidth() / imgWH);
					int y = (icon.getHeight() - oH) * 2 / 5;
					gc.drawImage(icon,0,0,w,h,0,y,icon.getWidth(),y + oH,null);
				}
				else if (iconWH < imgWH)
				{
					int oW = (int)(icon.getHeight() * imgWH);
					int x = (icon.getWidth() - oW) / 2;
					gc.drawImage(icon,0,0,w,h,x,0,x + oW,icon.getHeight(),null);
				}
				else
				{
					gc.drawImage(icon,0,0,w,h,null);
				}
			}

		}
		catch (IOException e)
		{
			throw new UnacceptableFileException(iconFile,e);
		}
		try
		{
			if (!indexed.exists())
				FileUtils.createNewFile(indexed);
			ImageIO.write(img,"jpg",indexed);
		}
		catch (Exception e)
		{
			throw new FailToSaveIndexException(indexed,e);
		}

	}

}
